package com.tyteam.apps.controller;

import java.io.File;
import java.io.IOException;
import java.lang.reflect.Method;
import java.util.ArrayList;
import java.util.Date;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.Set;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.sql.DataSource;

import org.apache.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Pageable;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.servlet.ModelAndView;

import com.shuohe.entity.system.user.User;
import com.shuohe.util.date.SDate;
import com.shuohe.util.easyuiBean.EasyUiDataGrid2;
import com.tyteam.apps.common.JsonResult;
import com.tyteam.apps.model.DynamicTask;
import com.tyteam.apps.model.UploadLog;
import com.tyteam.apps.service.UploadLogService;
import com.tyteam.apps.util.uploadUtil;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.bean.DynaBean;
import cn.hutool.core.collection.CollectionUtil;
import cn.hutool.core.io.FileUtil;
import cn.hutool.core.io.resource.ResourceUtil;
import cn.hutool.core.util.ClassLoaderUtil;
import cn.hutool.core.util.ClassUtil;
import cn.hutool.core.util.ReflectUtil;
import cn.hutool.db.Entity;
import cn.hutool.db.SqlRunner;
import cn.hutool.db.ds.DSFactory;
import cn.hutool.http.HttpUtil;
import cn.hutool.poi.excel.ExcelReader;
import cn.hutool.poi.excel.ExcelUtil;

@Controller
@RequestMapping("/upload")
public class UploadController {

	private final static Logger log = Logger.getLogger(UploadController.class.getName());

	// private FileUtil fUtil;
	//
	// private HttpUtil hUtil;
	// 真实路径
	@Value("${myPath.filePath}")
	private String filePath;

	@Value("${myPath.imgPath}")
	private String imgPath;

	@Value("${myPath.excelPath}")
	private String excelPath;

	@Value("${myPath.zipPath}")
	private String zipPath;
	// 调用路径
	private static String rfPath = "/upfile/files/";

	private static String riPath = "/upfile/img/";

	private static String rePath = "/upfile/excel/";

	private static String rzPath = "/upfile/zip/";

	private static String FILE = "file";

	private static String IMG = "img";

	private static String EXCEL = "excel";

	private static String ZIP = "zip";

	private String rootPath = "F:/uploadFile";

	@Autowired
	private UploadLogService uploadLogService;
	// 注入设备service
//	@Autowired
//	private EquipmentService equipmentService;

	@RequestMapping("")
	public ModelAndView index() {
		ModelAndView mv = new ModelAndView();
		mv.setViewName("fileManager/list");
		return mv;
	}

	@RequestMapping("getFilelist")
	@ResponseBody
	public EasyUiDataGrid2 getList(HttpServletRequest request, HttpServletResponse response) {
		User user = (User) request.getSession().getAttribute("user");
		String _page = request.getParameter("page");
		String _rows = request.getParameter("rows");
		int currentpage = Integer.parseInt(_page);
		int rows = Integer.parseInt(_rows);
		int firstResult = (currentpage - 1) * rows;
		Pageable pageable = new PageRequest(firstResult, rows);
		Page<UploadLog> page = uploadLogService.getPage(pageable);
		List<UploadLog> list = page.getContent();
		long count = page.getTotalElements();
		return new EasyUiDataGrid2(count, list);
	}

	@RequestMapping("add")
	public ModelAndView add() {
		ModelAndView mv = new ModelAndView();
		mv.setViewName("fileManager/add");
		return mv;
	}

	@RequestMapping("addPicture")
	public ModelAndView addPicture() {
		ModelAndView mv = new ModelAndView();
		mv.setViewName("fileManager/addPicture");
		return mv;
	}

	@RequestMapping(value = "preViewPdf")
	public ModelAndView preViewPdf(String filePath) {
		ModelAndView mv = new ModelAndView();
		mv.addObject("filePath", filePath);
		mv.setViewName("fileManager/pdfPreView");
		return mv;
	}

	@RequestMapping("addExc")
	public ModelAndView addExc() {
		ModelAndView mv = new ModelAndView();
		mv.setViewName("fileManager/addExcel");
		return mv;
	}

	@RequestMapping("addExcelSimple")
	public ModelAndView addExcelSimple() {
		ModelAndView mv = new ModelAndView();
		mv.setViewName("fileManager/addExcelSimple");
		return mv;
	}

	@RequestMapping(value = "deleteFile")
	@ResponseBody
	public JsonResult deleteFile(int id, String filePath) {
		JsonResult result = new JsonResult();
		FileUtil.del(filePath);
		uploadLogService.delete(id);
		result.setStatus("0");
		result.setMsg("删除成功");
		return result;
	}

	/**
	 * 上传多种类型文件
	 * 
	 * @param file
	 * @param path
	 * @param fileName
	 * @param addtional
	 * @return
	 * @throws Exception
	 */
	@RequestMapping(value = "/file", method = RequestMethod.POST)
	@ResponseBody
	public JsonResult uploadFile(@RequestParam("file") MultipartFile file, String fileType, HttpServletRequest request)
			throws Exception {
		JsonResult result = new JsonResult();
		User user = (User) request.getSession().getAttribute("user");
		String path = "";
		if (null != file) {
			if (FILE.equals(fileType)) {
				UploadLog up = uploadUtil.upload(file, filePath, rfPath);
				up.setUploadBy(user.getId());
				up.setUploadTime(new Date());
				UploadLog sta = uploadLogService.update(up);
				if (null != sta) {
					result.setObj(up);
					result.setStatus("0");
					result.setMsg("上传成功");
				} else {
					result.setStatus("1");
					result.setMsg("上传失败");
				}
			}
			if (IMG.equals(fileType)) {
				UploadLog up = uploadUtil.upload(file, imgPath, riPath);
				up.setUploadBy(user.getId());
				up.setUploadTime(new Date());
				UploadLog sta = uploadLogService.update(up);
				if (null != sta) {
					result.setObj(up);
					result.setStatus("0");
					result.setMsg("上传成功");
				} else {
					result.setStatus("1");
					result.setMsg("上传失败");
				}
			}
			if (EXCEL.equals(fileType)) {
				UploadLog up = uploadUtil.upload(file, excelPath, rePath);
				up.setUploadBy(user.getId());
				up.setUploadTime(new Date());
				UploadLog sta = uploadLogService.update(up);
				if (null != sta) {
					result.setObj(up);
					result.setStatus("0");
					result.setMsg("上传成功");
				} else {
					result.setStatus("1");
					result.setMsg("上传失败");
				}
			}
			if (ZIP.equals(fileType)) {
				UploadLog up = uploadUtil.upload(file, zipPath, rzPath);
				up.setUploadBy(user.getId());
				up.setUploadTime(new Date());
				UploadLog sta = uploadLogService.update(up);
				if (null != sta) {
					result.setObj(up);
					result.setStatus("0");
					result.setMsg("上传成功");
				} else {
					result.setStatus("1");
					result.setMsg("上传失败");
				}
			}
		} else {
			result.setMsg("上传失败，文件为空");
			result.setStatus("1");
		}
		return result;
	}

	@RequestMapping("getAllEntity")
	@ResponseBody
	public JsonResult getAllEntity() {
		JsonResult result = new JsonResult();
		Set set = ClassUtil.scanPackage("com.tyteam.apps.model");
		result.setObj(set);
		return result;
	}

	@RequestMapping("getMethod")
	@ResponseBody
	public JsonResult getMethod(String className) throws ClassNotFoundException {
		JsonResult result = new JsonResult();
		Class cla = Class.forName(className);
		Method[] me = ReflectUtil.getMethodsDirectly(cla, true);
		result.setObj(me);
		return result;
	}

	/**
	 * 导入excel到bean
	 * 
	 * @param file上传的excel文件
	 * @param modelClass导入类的类名，需包含包名
	 * @param methodClass调用方法的类名
	 * @param sqlMethod调用方法的执行方法
	 * @param request
	 * @return
	 * @throws Exception
	 */
	@SuppressWarnings("unchecked")
	@RequestMapping(value = "/importExcel", method = RequestMethod.POST)
	@ResponseBody
	public JsonResult importExcel(@RequestParam("file") MultipartFile file, String modelClass, String methodClass,
			String sqlMethod, HttpServletRequest request) throws Exception {
		JsonResult result = new JsonResult();
		User user = (User) request.getSession().getAttribute("user");
		System.out.println(modelClass);
		String path = "";
		UploadLog up = uploadUtil.upload(file, excelPath, rePath);
		up.setUploadBy(user.getId());
		up.setUploadTime(new Date());
		UploadLog sta = uploadLogService.update(up);
		if (null != sta) {
			// 获取执行方法的类
			// Class meClass = Class.forName(modelClass);
			// 实体类
			Class moClass = Class.forName(modelClass);
			// service类
			// Class meClass = getclass(methodClass);

			// 读取已经上传的文件
			ExcelReader reader = ExcelUtil.getReader(up.getFileRealPath());
			// 将读取的内容赋值给列表
			List<Map<String, Object>> readAll = reader.readAll();
			DataSource ds = DSFactory.get();
			SqlRunner runner = SqlRunner.create(ds);
			List<Entity> datas = new ArrayList<Entity>();
			for (Map<String, Object> cl : readAll) {
				System.out.println("数据：" + cl.toString());
				Class cla = BeanUtil.fillBeanWithMap(cl, moClass, true);
				Entity data = Entity.parse(cla);
				datas.add(data);
				// //转化实体类为bean

				// //通过反射工具，执行执行类的方法，并将列表中的内容传入
				// ReflectUtil.invoke(bean, method, bean);
				// method.invoke(meClass,cl);
			}
			int[] ret = runner.insert(datas);

			result.setObj(up);

			result.setStatus("0");
			result.setMsg("导入成功");
		} else {
			result.setStatus("1");
			result.setMsg("导入失败");
		}

		return result;
	}

	/**
	 * 读取excel导入的范例，仅供参考,使用方法来源于hutool，参见http://hutool.mydoc.io/?t=255684
	 * 注意，excel文件中标题列的名称，要与bean中的字段名一致！
	 * 
	 * @param file
	 * @param request
	 * @author liuyu
	 * @return
	 */
	@RequestMapping("impExlSimple")
	@ResponseBody
	public JsonResult impExlSimple(@RequestParam("file") MultipartFile file, HttpServletRequest request) {
		JsonResult result = new JsonResult();
		User user = (User) request.getSession().getAttribute("user");
		// 上传excel文件到上传文件夹下，正确上传完毕后，从该文件夹位置导入excel内容
		String path = "";
		UploadLog up = uploadUtil.upload(file, excelPath, rePath);
		up.setUploadBy(user.getId());
		up.setUploadTime(new Date());
		// boolean sta = uploadLogService.insertOrUpdate(up);
		// 1.读取文件，从文件路径读取文件内容
		ExcelReader reader = ExcelUtil.getReader(FileUtil.file(up.getFileRealPath()));

		// 2.从流中读取Excel为ExcelReader（比如从ClassPath中读取Excel文件）
		// ExcelReader reader =
		// ExcelUtil.getReader(ResourceUtil.getStream(up.getFileRealPath()));

		// 3.通过sheet编号获取
		// reader = ExcelUtil.getReader(FileUtil.file(up.getFileRealPath()), 0);

		// 4.通过sheet名获取
		// reader = ExcelUtil.getReader(FileUtil.file(up.getFileRealPath()), "sheet1");

		// 5.读取大数据量的Excel
		// private RowHandler createRowHandler() {
		// return new RowHandler() {
		// @Override
		// public void handle(int sheetIndex, int rowIndex, List<Object> rowlist) {
		// Console.log("[{}] [{}] {}", sheetIndex, rowIndex, rowlist);
		// }
		// };
		// }
		// ExcelUtil.readBySax("aaa.xlsx", 0, createRowHandler());

		// 1.读取Excel中所有行和列，都用列表表示
		// List<List<Object>> readAll = reader.read();

		// 2.读取为Map列表，默认第一行为标题行，Map中的key为标题，value为标题对应的单元格值。
		// List<Map<String,Object>> readAll = reader.readAll();

		// 3.读取为Bean列表，Bean中的字段名为标题，字段值为标题对应的单元格值。
		List<UploadLog> all = reader.readAll(UploadLog.class);
		// 读取后，使用循环方式将数据插入到对应实体类中
		try {
			for (UploadLog upl : all) {
				// upl.setUploadBy(user.getId());
				// upl.setUploadTime(new Date());
				uploadLogService.update(up);
			}
			result.setStatus("0");
			result.setMsg("导入成功");
		} catch (Exception e) {
			e.printStackTrace();
			result.setStatus("1");
			result.setMsg("导入失败");
		}

		return result;
	}

	public static Class getclass(String className)
			throws InstantiationException, IllegalAccessException, ClassNotFoundException// className是类名
	{
		Class obj = Class.forName(className).getClass(); // 以String类型的className实例化类
		return obj;
	}

	// 单张图片的上传
//	@SuppressWarnings("all")
//	@RequestMapping(value = "/imageFile", method = RequestMethod.POST)
//	@ResponseBody
//	public JsonResult uploadImage(@RequestParam("file") MultipartFile file, HttpServletRequest request)
//			throws Exception {
//		JsonResult result = new JsonResult();
//		User user = (User) request.getSession().getAttribute("user");
//		String equipment_id = request.getParameter("name");
//		log.info("临时的设备编号为：" + equipment_id);
//		String path = "";
//		String fty = file.getContentType();
//		String fileType = fty.substring(0, 5);
//		if (null != file) {
//
//			if ("image".equals(fileType)) {
//				UploadLog up = uploadUtil.upload(file, imgPath, riPath);
//				up.setUploadBy(user.getId());
//				up.setUploadTime(new Date());
//				UploadLog sta = uploadLogService.update(up);
//				EquipmentImage equipmentImage = new EquipmentImage();
//				equipmentImage.setFileName(up.getFileName());
//				equipmentImage.setEquipment_id(equipment_id);
//				equipmentImage.setFilePath(up.getFilePath());
//				equipmentImage.setFileType(up.getFileType());
//				equipmentImage.setFileRealPath(up.getFileRealPath());
//				equipmentImage.setUpdate_user(user.getId());
//				equipmentImage.setUploadTime(new Date());
//				if (null != sta) {
//					equipmentService.saveEquipmentImg(equipmentImage);
//					result.setObj(up);
//					result.setStatus("0");
//					result.setSuccess(true);
//					result.setMsg("上传成功");
//					result.setSrc(up.getFilePath());
//					result.setCode("200");
//				} else {
//					result.setSuccess(false);
//					result.setStatus("1");
//					result.setMsg("上传失败");
//					result.setCode("404");
//				}
//			} else {
//				result.setSuccess(false);
//				result.setStatus("1");
//				result.setMsg("只允许上传图片，请检查文件格式是否为图片");
//				result.setCode("404");
//			}
//
//			log.info("文件的类型为：" + fileType);
//		} else {
//			result.setMsg("上传失败，文件为空");
//			result.setStatus("1");
//			result.setCode("404");
//		}
//		return result;
//	}

}
